package com.whq.thrift.api.kafka.thriftlog.job;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.whq.thrift.api.common.constants.CommonConfigConstants;
import com.whq.thrift.api.common.spring.ReloadableConfManager;
import com.whq.thrift.api.kafka.thriftlog.db.ConsumeLog;

@Service
public class ClearOldConsumeLogJob {
	private static final Logger LOGGER = LoggerFactory.getLogger(ClearOldConsumeLogJob.class);
	private static final Logger LOGGER_QUARTZ = LoggerFactory.getLogger(CommonConfigConstants.LOGGER_KEY_QUARTZ);

	@Autowired
	private ReloadableConfManager reloadableConfManager;
	
	@Autowired
	private SqlSessionFactory sqlSessionFactory;

	
	public void removeOldConsumeLogData() {
		LOGGER_QUARTZ.info("begin remove old consume log");
//		String retainMaxDays = reloadableConfManager.getPropertyValue("consumelog.retain.max.days", null);
		int clearCount = reloadableConfManager.getIntPropertyValue("clear.table.count", null, 10);

//		int iRetainMaxDays = 0;
//		try {
//			iRetainMaxDays = Integer.valueOf(retainMaxDays);
//		} catch (Exception e) {
//			LOGGER.error("translate [" + retainMaxDays + "] to int exception", e);
//		}

		LOGGER_QUARTZ.info("will delete " + clearCount + " days before login logs");

		Date now = new Date(System.currentTimeMillis());
		ConsumeLog consumeLog = new ConsumeLog();
		consumeLog.setTimestamp(now);

		int tableSeq = consumeLog.getTableSeq();
		int tableSeqs = tableSeq + clearCount;
		
		for (int i = (tableSeq + 1); i <= tableSeqs; i++) {
			Map<String, Object> tmp = new HashMap<String, Object>();
			if (i > 131) {
				int j = i - 31;
				tmp.put("tableSeq", j);
			} else {
				tmp.put("tableSeq", i);
			}
			
			try {
				SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, true);
				sqlSession.update("ConsumeLogDao.dropTable", tmp);
				sqlSession.update("ConsumeLogDao.createTable", tmp);
//				sqlSession.commit();
				sqlSession.close();
			} catch (Exception e) {
				LOGGER.error("drop and create table exception: ", e);
			}
		}

		LOGGER_QUARTZ.info("end remove old login log");
	}

}
